from binance.um_futures import UMFutures
import time;
import requests
import datetime
from util.UTILS import *

url = 'https://kyb-api.520iy.com/public/sendWxMsg'

class ema_notice:
    def __init__(self,symbol,cal_interval,kline_type,client: UMFutures,logger,window):
        self.cal_start_time = time.time()
        self.cal_interval = cal_interval #计算间隔  单位 秒  上线后改成十分钟
        self.notice_time = time.time()
        self.notice_interval = 60*10 * 3 #十分钟

        self.symbol = symbol
        self.kline_type = kline_type
        self.client = client
        self.logger = logger
        self.window = window

    def send_msg(self,openid, one, two, diff):
        if time.time() - self.notice_time > self.notice_interval:

            paras = {}
            paras['openid'] = openid
            msg = {}
            paras['msg'] = msg

            msg['type'] = 'income_msg'
            msg['one'] = one
            msg['two'] = two
            msg['diff'] = diff

            msg['time'] = ''
            response = requests.post(url, json=paras)
            #更新间隔
            self.notice_time = time.time()
        else:
            self.logger.info("重复通知 合约：{}  上次通知时间{}".format(one,self.notice_time))


    def calculate_ema(self,data, window):
        """
        计算时间序列数据的指数移动平均值 (EMA)。

        参数:
        - data: list 或 numpy array, 时间序列数据。
        - window: int, EMA的时间窗口（平滑系数的基础）。

        返回:
        - ema: list, 计算后的 EMA 值。
        """
        if not data or len(data) < window:
            raise ValueError("数据长度必须大于时间窗口")

        alpha = 2 / (window + 1)  # EMA 平滑系数
        ema = [data[0]]  # 初始化第一个 EMA 值为第一个数据点

        for i in range(1, len(data)):
            ema_value = alpha * data[i] + (1 - alpha) * ema[-1]
            ema.append(ema_value)

        return ema

    def monitor_price(self):
        if time.time() - self.cal_start_time > self.cal_interval:
            #根据 计算间隔 self.cal_interval 执行计算函数
            self.cal_start_time = time.time()

            result = self.client.mark_price(symbol=self.symbol);
            markPrice = float(result['markPrice']);

            kline_data = self.client.klines(symbol=self.symbol, interval=self.kline_type, limit=200);
            data = [];
            for item in kline_data:
                price = float(item[1]);
                data.append(price);
            ema_array = self.calculate_ema(data, self.window)
            ema_price = ema_array[-1];

            if markPrice < ema_price:
                # 标记价格低于
                msg_one = '合约:  {}   K线类型:{}'.format(self.symbol, self.kline_type)
                msg_two = 'ema:  {}'.format(ema_price)
                msg_diff = '合约价格:  {}'.format(markPrice)
                # self.send_msg('ocAr152-22tVKGt2Fp-E9GZ06Oos', one=msg_one, two=msg_two, diff=msg_diff)
                # self.send_msg('ocAr157l0xBsK2-WVZKjuPn0rzfs', one=msg_one, two=msg_two, diff=msg_diff)
                # self.send_msg('ocAr158EKzaSyrUH_D91DDq6ipxs', one=msg_one, two=msg_two, diff=msg_diff)
                self.send_msg('ocAr1534Q295U02-OvVaQDnsIsNY', one=msg_one, two=msg_two, diff=msg_diff)

                self.send_msg('ocAr15_V5VzRThpYYZCVg3aY0-As', one=msg_one, two=msg_two, diff=msg_diff)

                self.logger.info("symbol :{}  kline_type:{}   ema_price:{}   markPrice:{}".format(self.symbol,self.kline_type,ema_price,markPrice))
                #更新上次计算的时间
                self.start_time = time.time()

                return True
            else:
                return False



if __name__ == '__main__':
    um_futures_client = UMFutures()
    logger = getLogger("ema_notice")
    day_interval = "1d"
    cal_interval = 6  # 每5秒触发一次检测（单位：秒）
    btc_ema_notice_d = ema_notice('BTCUSDT',cal_interval,day_interval,um_futures_client,logger,25)
    eth_ema_notice_d = ema_notice('ETHUSDT',cal_interval,day_interval,um_futures_client,logger,25)
    doge_ema_notice_d = ema_notice('DOGEUSDT',cal_interval,day_interval,um_futures_client,logger,25)

    btc_ema_notice_4h = ema_notice('BTCUSDT', cal_interval, '4h', um_futures_client,logger,25)
    eth_ema_notice_4h = ema_notice('ETHUSDT', cal_interval, '4h', um_futures_client,logger,25)
    doge_ema_notice_4h = ema_notice('DOGEUSDT', cal_interval, '4h', um_futures_client,logger,25)

    while True:
        try:
            btc_ema_notice_d.monitor_price()
            eth_ema_notice_d.monitor_price()
            doge_ema_notice_d.monitor_price()

            btc_ema_notice_4h.monitor_price()
            eth_ema_notice_4h.monitor_price()
            doge_ema_notice_4h.monitor_price()
            time.sleep(1)
        except Exception as e:
            logger.error("monitor_price :",e)
